package com.jblv.frame.common.logger;

import ch.qos.logback.classic.Level;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.logging.log4j.spi.LoggerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author happyonion.yangtao
 * @version 1.0
 * @title LoggerAdapterFactory
 * @projectName jblv-frame
 * @packageName com.jblv.frame.common.plugin
 * @description LoggerAdapterFactory
 * @date Create at 2020/5/11 9:49
 * @since jdk1.8
 */
public class LoggerAdapterFactory {


    public static void trace(String msg) {
        getLogger().trace(msg);
    }

    public static void debug(String msg) {
        getLogger().debug(msg);
    }

    public static void info(String msg) {
        getLogger().info(msg);
    }

    public static void warn(String msg) {
        getLogger().warn(msg);
    }

    public static void error(String msg) {
        getLogger().error(msg);
    }

    public static void error(String msg,Throwable t) {
        getLogger().error(msg,t);
    }

    private static Logger getLogger() {
        return LoggerFactory.getLogger(findCaller().getClassName());
    }

    private static StackTraceElement findCaller() {
        // 获取堆栈信息
        StackTraceElement[] callStack = Thread.currentThread().getStackTrace();

        // 最原始被调用的堆栈信息
        StackTraceElement caller = null;

        // 日志类名称

        String logClassName = LoggerAdapterFactory.class.getName();
        // 循环遍历到日志类标识

        int i = 0;
        for (int len = callStack.length; i < len; i++) {
            if (logClassName.equals(callStack[i].getClassName())) {
                break;
            }
        }
        //是的没有错,这是一个magic number！想知道为什么？开启你的堆栈，来寻找我的宝藏吧！by Luo
        caller = callStack[i + 3];
        return caller;
    }


    public static void init(Properties properties) {
        if (!"true".equals(properties.getProperty("logger.out.custom", "false"))) {
            return;
        }
        LoggerAdapterSetter setter = new LoggerAdapterSetter();
        setter.setCustom("true".equals(properties.getProperty("logger.out.custom", "false")));
        setter.setLogback("true".equals(properties.getProperty("logger.out.logback", "true")));
        setter.setLoggerLevel(properties.getProperty("logger.out.level", "info"));
        String appId = properties.getProperty("jblv.application.id");
        setter.setAppId(appId);
        String host = properties.getProperty("jblv.application.host");
        setter.setLocalHost(host);
        setter.setAccessConfigCenter(true);
//        getLogger(LoggerAdapterFactory.class, Level.INFO).info(appId + " [" + host + "] logger adapter setter config initialized");
    }


}
